package com.atguigu.search.service.impl;

import com.atguigu.param.ProductSearchParam;
import com.atguigu.pojo.Product;
import com.atguigu.pojo.ProductDoc;
import com.atguigu.search.service.SearchService;
import com.atguigu.utils.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.util.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    RestHighLevelClient client; //客户端

    @Override
    public R product(ProductSearchParam productSearchParam) {

        SearchRequest searchRequest = new SearchRequest("product");
        // 关键字为空，则匹配全部
        if(StringUtils.isNullOrEmpty(productSearchParam.getSearch())){
            searchRequest.source().query(QueryBuilders.matchAllQuery());
        }else{// 否则，按all字段模糊查询
            searchRequest.source().query(QueryBuilders.matchQuery("all",productSearchParam.getSearch()));
        }
        
        // 设置分页
        searchRequest.source().from(productSearchParam.getFrom());//设置偏移量
        searchRequest.source().size(productSearchParam.getSize());

        SearchResponse response = null;
        try {
            response=client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        //结果集解析
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;

        SearchHit[] items = hits.getHits();
        ArrayList<Product> products = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        //将json字符串解析为product对象
        for (SearchHit item : items) {
            String json = item.getSourceAsString();
            Product product = null;
            try {
                // 多字段转为少字段，要记得加注解@JsonIgnoreProperties(ignoreUnknown = true) //忽略多余的字段
                product = objectMapper.readValue(json, Product.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            products.add(product);

        }

        return R.ok("es查询成功",products,total);
    }

    // 更新es库
    @Override
    public R save(Product product) throws IOException {

        IndexRequest indexRequest = new IndexRequest("product").id(product.getProductId().toString());

        ProductDoc productDoc = new ProductDoc(product);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(productDoc);
        indexRequest.source(json, XContentType.JSON);

        client.index(indexRequest,RequestOptions.DEFAULT);
        return R.ok("更新es库成功");
    }

    @Override
    public R remove(Integer productId) throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("product").id(productId.toString());
        client.delete(deleteRequest, RequestOptions.DEFAULT);
        return R.ok("删除es库成功");
    }
}
